package edu.hawaii.myisern.model;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Logs events.
 * 
 * @author Randy Cox
 */
public class Log {

  /** Path and filename for the event log. */
  public static final String LOG_FILENAME = System.getProperty("user.home")
      + "/.myisern/myisern.log";

  /** Verbose flag to send logging to standard out. */
  public static boolean verbose = true;

  /** Severe only flag to send logging for errors only. */
  public static boolean severeOnly = false;

  /** Stores logging variable. */
  private static Logger log = null;

  /** Log file to write too. */
  private static File logFile = null;

  /**
   * Creates and initializes log.
   */
  private static void initialize() {

    // Create directory if not present.
    File myIsernHome = new File(System.getProperty("user.home"), "/.myisern");
    myIsernHome.mkdirs();

    // Set up logger
    Log.log = Logger.getLogger("edu.hawaii.myisern.model");
    Log.log.setUseParentHandlers(false);
    Handler[] handlers = Log.log.getHandlers();
    if (handlers.length == 0) {
      Handler handler = new LogHandler();
      Log.log.addHandler(handler);
    }
  }

  /**
   * Clear log file.
   * 
   */
  public static void clear() {

    // Open log file for appending.
    initialize();
    logFile = new File(Log.LOG_FILENAME);
    FileWriter fileWriter = null;
    try {
      fileWriter = new FileWriter(logFile, false);
      fileWriter.flush();
      fileWriter.close();
    }
    catch (IOException e) {
      System.err.println("Log StandardHander.clear(): I/O error with log file:" + Log.LOG_FILENAME);
    }
  }

  /**
   * Send message to be logged.
   * 
   * @param message string to be logged.
   */
  public static void enter(String message) {
    initialize();
    if (!Log.severeOnly) {
      Log.log.log(Level.INFO, message);
    }
  }

  /**
   * Send message to be logged.
   * 
   * @param message string to be logged.
   */
  public static void error(String message) {
    initialize();
    Log.log.log(Level.SEVERE, message);
  }

}
